<html>
<head><title>Awesomegotchi</title></head>
<body>
<h1><center>AWESOMEGOTCHI!</center></h1>
<h3><center>A Superawesome Proximity Based Gaming Experience For Social Networking</center></h3>
<font size=1><center>(which is awesome)</center></font>
<?php
	ini_set( "display_errors", 0);
	//Default page authorising the user, and putting their data in the database.
	include 'configuration.php';

	if(isset($_GET['code']))
	{
		//get access token
		$token = explode('=', file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$APP_ID&redirect_uri=http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]&client_secret=$APP_SECRET&code=" . (get_magic_quotes_gpc() ? stripslashes($_GET['code']) : $_GET['code'])));

		//get user info
		$user_info = json_decode(file_get_contents("https://graph.facebook.com/me?access_token=$token[1]"));
		$id = $user_info->{'id'};
		$name = $user_info->{'name'};
		//echo "<p>Hi, $name, you have authorized this application. The tamagotchi is now integrated with your facebook</p>";

		//insert values into the database
		$link = mysql_connect('localhost', $DBUSER, $DBPASS) or die('Could not connect: ' . mysql_error());
		mysql_select_db('facebook') or die('Could not select database');
		
		$friends_ids = json_decode(file_get_contents("https://graph.facebook.com/me/friends?access_token=$token[1]&fields=id"));
		
		//download a friends list
		$friend_string = '';
		foreach($friends_ids->{'data'} as $friend_id)
		{
			$fid = $friend_id->{'id'};
			$friend_string = $friend_string . $friend_id->{'id'};
			if (mysql_num_rows(mysql_query("SELECT id FROM users WHERE id='$fid'")))
			{
				//if this friend is using our application:
				if (!(mysql_num_rows(mysql_query("SELECT id1 FROM friends WHERE friendsid='$id$fid'"))))
				{
					//if we don't have this friendship in the database:
					mysql_query("insert into friends values ('$id', '$fid')");
					mysql_query("insert into friends values ('$fid', '$id')");
				}
			}
		}
		//compute a friends hash
		$friends_hash = md5($friend_string);
		
		//check if there were any removed friends:
		$result = mysql_query("select id2 from friends where id1=$id");
		//$row = mysql_fetch_array($result, MYSQL_NUM);
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
			if (!in_array($line['id2'], $friends_ids->{'data'}))
			{
				//if the friend we store is not in friend list anymore:
				mysql_query("delete from friends where friends_id = '$id$fid'");
				mysql_query("delete from friends where friends_id = '$fid$id'");
			}
		}
		mysql_free_result($result);
		
		if(mysql_num_rows(mysql_query("SELECT id FROM users WHERE id = '$id'"))){
			//if the user is already in the database
			$query = "update users set name='$name', access_token='$token[1]', friends_hash='$friends_hash' where id='$id'";
		}
		else
		{
			//if we don't have any records about the user
			$query = "insert into users values ('$id', '$name', '$token[1]', '$friends_hash', '', 0)";
		}
		$result = mysql_query($query) or die('fail'.mysql_error());
		
		echo "<center><table><tr><td>Hi, $name<br/>";
		echo '<form action="change_ip.php" method="post">';
		echo "<input type=\"hidden\" name=\"id\" value=\"$id\"/>";
		echo "<input type=\"hidden\" name=\"code\" value=\"".$_GET['code']."\"/>";
		$result = mysql_query("select address from users where id='$id'");
		$row = mysql_fetch_array($result, MYSQL_NUM);
		$addr = $row[0];
		if ($addr=='')
		{
			echo "Only one step before you can take part in the awesome game of rock-paper-scissors!<br/>Enter the IP address of your Awesomegotchi device below:<br/>";
		}
		else
		{
			echo "Your device's IP address is $addr.<br/>You can change it below:<br/>";
		}
		echo "<input type=\"text\" name=\"ip\" value=\"$addr\"/>";
		echo "<input type=\"submit\" value=\"OK\" />";
		echo '</form>';
		echo "</td><td>";
		
		echo "<h3>Our Scoreboard:</h3><table>";
		$result = mysql_query("select id, name, score from users order by score desc");
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
			echo "<tr><td><a href=\"http://www.facebook.com/profile.php?id=".$line['id']."\">".$line['name']."</a></td><td>".$line['score']."<td></tr>";
		}
		mysql_free_result($result);
		echo "</table>";
		echo "</td></tr></table></center>";
		
		
		mysql_close($link);
	}
	else
	{
		//redirect the user to the authorisation page
		echo "<script>\n";
		echo "  lhref = location.href;\n";
		echo "  if (lhref.indexOf('code=')==-1)\n";
		echo "  {\n";
		echo "	window.location = 'https://graph.facebook.com/oauth/authorize?client_id=$APP_ID&redirect_uri=http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]&scope=publish_stream,offline_access&display=page'\n";	echo "  }\n";
		echo "</script>\n";
	}
	echo "</body></html>"
?>